<template>
  <div>
    <a-modal
      :title="selectLevel+'选择'"
      :visible="visible"
      width="600px"
      :maskClosable="false"
      @ok="handleOk"
      @cancel="handleCancel"
      wrapClassName="province-city-modal-Lu"
    >
      <div>
        <div>
          <a-select
            show-search
            :value="value"
            placeholder="请输入省份/城市/区县搜索"
            style="width: 200px"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            @search="handleSearch"
            @change="handleChange"
            @popupScroll="handlePopupScroll"
            class="search-input"
          >
            <a-select-option v-for="(item,index) in frontBatchCode" :key="index" @click="getSearchData(item)">
              <span v-html="item"></span>
            </a-select-option>
          </a-select>
        </div>
        <div class="checkbox" style="">
          <div v-if="selectLevel.indexOf('省') !== -1">
            <h2>省份</h2>
              <a-select default-value="xx壮族自治区" v-model="formState.provice" size="default" style="width: 160px" >
                <a-select-option v-for="(item,index) in proviceList" :key="index" :value="item.name" @click="proviceChange(item)">
                  {{ item.name }}
                </a-select-option>
              </a-select>
          </div>
          <div v-if="selectLevel.indexOf('市') !== -1">
            <h2>城市</h2>
            <a-select v-model="formState.city" size="default" style="width: 200px">
              <a-select-option v-for="(item,index) in cityList" :key="index" :value="item.name" @click="cityChange(item)">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </div>
          <div v-if="selectLevel.indexOf('区') !== -1">
            <h2>区县</h2>
            <a-select v-model="formState.area" size="default" style="width: 220px">
              <a-select-option v-for="(item,index) in areaList" :key="index" :value="item.name" @click="areaChange(item)">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </div>
        </div>
      </div>
      <template slot="footer">
        <a-button @click="handleCancel">取消</a-button>
        <a-button :disabled="isClick()" :class="handleOkBtn ?'grey-btn':'blue-btn'" @click="handleOk">确定</a-button>
      </template>
    </a-modal>
  </div>
</template>
<script>
import { provinceFunction,cityFunction,areaFunction,searchFunction } from './index'
export default {
  props: {
    // 需要的数据层级，如：省/市/区
    selectLevel: {
        type:String,
        default: '',
        required:false
    }
  },
  watch:{
    visible: {
      handler(newval, oldVal){
          // //console.log(newval)
          if(newval){
              this.getProvince()
          }
      }
    }
  },
  data() {
    return {
      visible: false,
      proviceList: [],
      cityList: [],
      areaList: [],
      formState: {
        provice: 'xx壮族自治区',
        city: '',
        area: '',
      },
      defaultProvice: 'xx壮族自治区',
      value: undefined,
      searchValue: '',
      listBatchCode: [],//batchCode的总数据（不会改变）
      frontBatchCode: [], //存放前100的数据
      allData: [],
      valueData: '',    //batchCode输入或选择的值
      treePageSize: 100,
      scrollPage: 1,
      url:{
        batchCodeList: "/batch/component/allBatchCode"
      },
      handleOkBtn: false
    };
  },
  methods: {
    handleSearch(value) {
      this.searchValue = value
      // fetch(value, frontBatchCode => (this.frontBatchCode = frontBatchCode));
      searchFunction({gjz:value}).then(res => {
        this.listBatchCode = res.result
        this.frontBatchCode = res.result.slice(0,100)
        // //console.log('value',value)
        this.frontBatchCode = this.frontBatchCode.map((item)=>{
          let replaceReg = new RegExp(value,'g');
          let replacecontent ='<span style="color:#ff8517">'+ value + '</span>';
          if (item.includes(value)) {
            item = item.replace( replaceReg,replacecontent);
          }
          return item;
        })
      })
    },
    handleChange(value) {
      // //console.log(value);
      this.value = value;
      // fetch(value, frontBatchCode => (this.frontBatchCode = frontBatchCode));
    },
    handlePopupScroll(e){
      // //console.log('滚动时',e)
      const { target } = e
      const scrollHeight = target.scrollHeight - target.scrollTop
      const clientHeight = target.clientHeight
      // 下拉框不下拉的时候
      if (scrollHeight === 0 && clientHeight === 0) {
        this.scrollPage = 1
        // //console.log(this.scrollPage)
      } else {
        // 当下拉框滚动条到达底部的时候
        // //console.log(scrollHeight,clientHeight,clientHeight + 5)
        if (scrollHeight - clientHeight == 0) {
        // if (scrollHeight < clientHeight + 5) {
          // //console.log('当下拉框滚动条到达底部的时候')
          this.scrollPage = this.scrollPage + 1
          const scrollPage = this.scrollPage// 获取当前页
          const treePageSize = this.treePageSize * (scrollPage || 1)// 新增数据量
          const newData = [] // 存储新增数据
          let max = '' // max 为能展示的数据的最大条数
          if (this.listBatchCode.length > treePageSize) {
            // 如果总数据的条数大于需要展示的数据
            max = treePageSize
          } else {
            // 否则
            max = this.listBatchCode.length
          }
          // 判断是否有搜索
          if (this.valueData) {
            this.allData.forEach((item, index) => {
              if (index < max) { // 当data数组的下标小于max时
                newData.push(item)
              }
            })
          } else {
            this.listBatchCode.forEach((item, index) => {
              if (index < max) { // 当data数组的下标小于max时
                newData.push(item)
              }
            })
          }
          this.frontBatchCode= newData // 将新增的数据赋值到要显示的数组中
          // //console.log('this.searchValue',this.searchValue)
          this.frontBatchCode = this.frontBatchCode.map((item)=>{
            let replaceReg = new RegExp(this.searchValue,'g');
            let replacecontent ='<span style="color:#ff8517">'+ this.searchValue + '</span>';
            if (item.includes(this.searchValue)) {
              item = item.replace( replaceReg,replacecontent);
            }
            return item;
          })
        }
      }
    },
    keyText(h){
      const vnodes = [];
      const text = this.value
      text.forEach(str => {
        vnodes.push(h('span', null, str))
        vnodes.push(h('span', { style: 'color: #0FBDA0' }))
      })
      if (text.length > 0) {
        vnodes.pop()
      }
      return h('span', null, vnodes)
    },
    //---
    getProvince(){
      this.formState.provice = this.defaultProvice
      provinceFunction().then(res => {
        // //console.log(res)
        this.proviceList = res.result
        // let arr = res.result
        // let array = JSON.parse(JSON.stringify(arr).replace(/name/g,"label").replace(/code/g,"value").replace(/cchilds/g,"children"))
        // //console.log('转换后---',array)
        // this.options = array
        const dataSource = [...this.proviceList]
        const target = dataSource.find(item => item.name == this.defaultProvice)
        // //console.log(this.defaultProvice)
        // //console.log(target)
        if(target){
          this.defaultCity(target)
        }
      })
    },
    defaultCity(val){
      cityFunction({code:val.code}).then(res => {
        this.cityList = res.result
        this.formState.city = ''
        this.formState.area = ''
        this.areaList = []
      })
    },
    proviceChange(val){
      this.formState.provice = val.name
      cityFunction({code:val.code}).then(res => {
        this.cityList = res.result
        this.formState.city = ''
        this.formState.area = ''
        this.areaList = []
      })
    },
    cityChange(val){
      this.formState.city = val.name
      //console.log(this.formState)
      areaFunction({code:val.code}).then(res => {
        this.areaList = res.result
        this.formState.area = ''
      })
    },
    areaChange(val){
      this.formState.area = val.name
      //console.log(val)
    },
    handleOk(){
      let str = this.formState.provice + this.formState.city + this.formState.area
      let dataForm = {
        provice: this.formState.provice,
        city: this.formState.city,
        area: this.formState.area
      }
      //console.log(dataForm)
      this.$emit('selectAddressHandle',str,dataForm)
      this.handleCancel()
    },
    //
    isClick(){
      if(this.selectLevel.indexOf('省') !== -1){
        if(this.formState.provice == ''){
          this.handleOkBtn = true
          return true
        }
      }
      if(this.selectLevel.indexOf('市') !== -1){
        if(this.formState.city == ''){
          this.handleOkBtn = true
          return true
        }
      }
      if(this.selectLevel.indexOf('区') !== -1){
        if(this.formState.area == ''){
          this.handleOkBtn = true
          return true
        }
      }
      this.handleOkBtn = false
      return false
    },
    getSearchData(val){
      // 筛选字符串中的汉字->数组转为字符串
      let str =   val.match(/[\u4e00-\u9fa5]/g).join("")
      // //console.log(val)
      // //console.log(str)
      this.$emit('selectAddressHandle',str)
      this.handleCancel()
    },
    handleCancel(){
      this.visible = false
      this.proviceList = []
      this.cityList = []
      this.areaList = []
      this.formState.provice = ''
      this.formState.city = ''
      this.formState.area = ''
    },
  },
};
</script>
<style lang="less">
.province-city-modal-Lu {
  margin: 0 auto;
  .search-input {
    width: 100% !important;
    .ant-select-selection {
      border-radius: 20px;
    }
  }
  .checkbox {
    display: flex;
    justify-content: space-around;
    margin-top: 20px;
    div {
      text-align: center;
    }
  }
  .ant-modal-content {
    border-radius: 10px;
    font-family: KaiTi!important;
    .ant-modal-header {
      background-color: transparent;
    }
  }
  .grey-btn {
    background-color: grey;
    color: white;
  }
}
</style>
